//
//  KeyboardTool.m
//  Runner
//
//  Created by mini2025 on 2025/10/11.
//

#import "KeyboardTool.h"
#import <Cocoa/Cocoa.h>
#import <Carbon/Carbon.h>


static CGEventRef eventCallback(CGEventTapProxy proxy, CGEventType type, CGEventRef event, void *refcon) {
    if (type == kCGEventKeyDown) {
        CGKeyCode key = (CGKeyCode)CGEventGetIntegerValueField(event, kCGKeyboardEventKeycode);
        // 检测快捷键，比如 Command + Shift + T
        CGEventFlags flags = CGEventGetFlags(event);
        if ((flags & kCGEventFlagMaskCommand) && (flags & kCGEventFlagMaskShift) && key == kVK_ANSI_A) {
            NSLog(@"Command + Shift + A pressed!");
            
        }
    }
    return event;
}


@implementation KeyboardTool

+ (void)startListenKeyboard{
    CGEventMask mask = CGEventMaskBit(kCGEventKeyDown);
    CFMachPortRef eventTap = CGEventTapCreate(
        kCGSessionEventTap,
        kCGHeadInsertEventTap,
        kCGEventTapOptionListenOnly,
        mask,
        eventCallback,
        NULL
    );
    if (!eventTap) {
        NSLog(@"Failed to create event tap");
        return;
    }
    CFRunLoopSourceRef runLoopSource = CFMachPortCreateRunLoopSource(kCFAllocatorDefault, eventTap, 0);
    CFRunLoopAddSource(CFRunLoopGetCurrent(), runLoopSource, kCFRunLoopCommonModes);
    CGEventTapEnable(eventTap, true);
    CFRunLoopRun();
}

@end
